#include "List.h"

LTNode* CreateList(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));

	if (newnode == NULL)
	{
		perror("newnode malloc");
		return NULL;
	}
	newnode->next = NULL;
	newnode->data = x;
	newnode->prev = NULL;

	return newnode;
}

LTNode* LTInit()
{
	LTNode* phead = CreateList(-1);

	phead->next = phead;
	phead->prev = phead;

	return phead;

}


void PushBack(LTNode* head, LTDataType x)
{
	assert(head);

	/*LTNode* newnode = CreateList(x);
	LTNode* tail = head->prev;

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = head;
	head->prev = newnode;*/
	ListInsert(head, x);


}


void PushFront(LTNode* head, LTDataType x)
{
	assert(head);

	/*LTNode* newnode = CreateList(x);
	LTNode* tail=head->next;
	newnode->next = head->next;
	newnode->prev = head;
	tail->prev = newnode;
	head->next = newnode;*/
	ListInsert(head->next, x);
}

void LTPrin(LTNode* phead)
{
	assert(phead);

	printf("<=head=>");
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

bool Empty(LTNode* head)
{
	assert(head);

	return head->next == head;
}


void PopFront(LTNode* head)
{
	assert(head);

	assert(!Empty(head));
	/*LTNode* tail = head->next;
	head->next = head->next->next;

	free(tail);
	tail = NULL;*/
	ListErase(head->next);

}

void PophBack(LTNode* head)
{
	assert(head);
	assert(!(Empty(head)));

	/*LTNode* tail = head->prev;
	LTNode* tailprev = tail->prev;

	tailprev->next = head;
	head->prev = tailprev;

	free(tail);
	tail = NULL;*/
	ListErase(head->prev);

}


void ListInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* prev = pos->prev;
	LTNode* newnode = CreateList(x);
	newnode->next = pos;
	newnode->prev = prev;
	pos->prev = newnode;
	prev->next = newnode;
}

LTNode* ListFind(LTNode* head, LTDataType x)
{
	assert(head);

	LTNode* cur = head;
	while (cur->data != x)
	{
		cur = cur->next;
	}

	return cur;
	
}

void ListErase(LTNode* pos)
{
	assert(pos);
	LTNode* tail = pos;
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
	free(tail);
	tail = NULL;
}